<script setup lang='ts'>
import { ref, computed, watch } from 'vue'
import type { StoryItem } from '../../../apis/story/type';
import type { ProjectMember } from '../../../apis/project/type';
import { ElMessage, ElMessageBox } from 'element-plus';
import { reqChangeStoryStatus } from '../../../apis/story';
import { reqUpdateProjectStoryBystory } from '../../../apis/story';
import { formatDateISOS } from '../../../utils/time';

const props = defineProps<{
  rowData: StoryItem
  memberList: ProjectMember[]
}>()
const dialogVisible = defineModel('dialogVisible')
const localData = ref<StoryItem>(JSON.parse(JSON.stringify(props.rowData)))
const emit = defineEmits(['refresh'])

const statusOptions = computed(() => {
  const options = [
    { value: 'new', label: '新建' },
    { value: 'in-progress', label: '实现中' },
    { value: 'completed', label: '已实现' },
    { value: 'rejected', label: '已拒绝' }
  ]

  // 根据当前状态过滤可选项
  let filteredOptions = []
  switch (props.rowData.status) {
    case 'new':
      filteredOptions = options.filter(opt => ['new', 'in-progress', 'rejected'].includes(opt.value))
      break
    case 'in-progress':
      filteredOptions = options.filter(opt => ['in-progress', 'completed', 'rejected'].includes(opt.value))
      break
    case 'completed':
      filteredOptions = options.filter(opt => ['completed', 'in-progress'].includes(opt.value))
      break
    case 'rejected':
      filteredOptions = options.filter(opt => ['rejected', 'in-progress'].includes(opt.value))
      break
    default:
      filteredOptions = options
  }

  // 将当前状态选项移到第一个位置
  const currentStatusOption = filteredOptions.find(opt => opt.value === props.rowData.status)
  const otherOptions = filteredOptions.filter(opt => opt.value !== props.rowData.status)

  return currentStatusOption ? [currentStatusOption, ...otherOptions] : filteredOptions
})

const getStatusName = (status: string) => {
  const statusNameMap: { [key: string]: string } = {
    'new': '新建',
    'in-progress': '实现中',
    'completed': '已实现',
    'rejected': '已拒绝'
  }
  return statusNameMap[status] || status
}

const handleChangeStatus = async () => {
  if (!localData.value.assignees || localData.value.assignees.length === 0) {
    ElMessage.error('请选择至少一个处理人')
    return
  }

  ElMessageBox.confirm(`确定更改状态为${getStatusName(localData.value.status)}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let assigneeIds = localData.value.assignees ? localData.value.assignees.map((item: any) => item.id) : []
    const [statusRes, updateRes] = await Promise.all([reqChangeStoryStatus(localData.value.projectId, localData.value.id, localData.value.status),
    reqUpdateProjectStoryBystory(localData.value.projectId, localData.value.id, {
      title: localData.value.title,
      description: localData.value.description,
      parentId: localData.value.parentId,
      priority: localData.value.priority,
      endsAt: localData.value.endsAt ? formatDateISOS(localData.value.endsAt) : null,
      assigneeIds: assigneeIds,
    })])
    if (statusRes.code === 200 && updateRes.code === 200) {
      ElMessage.success('更改成功')
      dialogVisible.value = false
      emit('refresh')
    }
  })
}

watch(() => props.rowData, (newVal) => {
  localData.value = JSON.parse(JSON.stringify(newVal))
}, { deep: true })
</script>


<template>
  <el-dialog v-model="dialogVisible" width="600" align-center :modal="false" draggable>
    <template #header>
      <p style="font-size: 24px;font-weight: 600;">更改状态</p>
    </template>
    <el-tabs tab-position="left" style="height: auto;padding: 10px 0;" class="demo-tabs" v-if="dialogVisible"
      v-model="localData.status">
      <el-tab-pane v-for="item in statusOptions" :name="item.value">
        <template #label>
          <el-button :type="item.value === 'new' ? 'primary' :
            item.value === 'in-progress' ? 'warning' :
              item.value === 'completed' ? 'success' :
                'danger'" size="small" round>{{ item.label }}</el-button>
        </template>
        <div class="tabs_content">
          <div class="tab_handler" style="display: flex;align-self: center;">
            <p style="margin: 0 50px 20px 10px;">处理人</p>
            <div class="m-4" width="250">
              <el-select v-model="localData.assignees" multiple collapse-tags collapse-tags-tooltip placeholder="请选择处理人"
                style="width: 300px" value-key="id">
                <el-option v-for="item in memberList" :key="item.id" :label="item.username" :value="item" />
              </el-select>
            </div>
          </div>
          <div class="tabs_comments" style="display: flex;">
            <p style="margin: 0px 64px 10px 10px;">内容</p>
            <el-input style="width: 300px;" v-model="localData.description" type="textarea" rows="10"
              placeholder="可以在此更改内容喔~"></el-input>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangeStatus">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>


<style scoped lang='scss'></style>